package flc.ast.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.activity.LocalVideoActivity;
import flc.ast.activity.PlayLandscapeActivity;
import flc.ast.activity.PrivacyVideoActivity;
import flc.ast.activity.VideoLibraryActivity;
import flc.ast.adapter.HomeVideoAdapter;
import flc.ast.adapter.VideoLibraryAdapter;
import flc.ast.databinding.FragmentPlayBinding;
import flc.ast.dialog.ChangePasswordDialog;
import flc.ast.dialog.EditDialog;
import flc.ast.dialog.SetAnswerDialog;
import flc.ast.dialog.SetPasswordDialog;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.SPUtil;
import stark.common.basic.utils.StkPermissionHelper;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link PlayFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class PlayFragment extends BaseNoModelFragment<FragmentPlayBinding> {

    private List<String> listShow = new ArrayList<>();
    private HomeVideoAdapter videoAdapter;
    private VideoLibraryAdapter videoLibraryAdapter;
    private Dialog myAddVideoLibraryDialog, myDeleteDialog, myRenameDialog;
    private EditText dialogAdd, dialogRename;
    private BasePopupView editPopup, changePasswordPopup;
    private int selPosition;
    private String pwd;


    @Override
    protected int onCreate() {
        return R.layout.fragment_play;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mDataBinding.tvGetPermission.setOnClickListener(this);
        mDataBinding.tvAllVideo.setOnClickListener(this);

        mDataBinding.rvVideoList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        videoAdapter = new HomeVideoAdapter();
        mDataBinding.rvVideoList.setAdapter(videoAdapter);
        videoAdapter.setOnItemClickListener(this);

        mDataBinding.rvVideoLibraryList.setLayoutManager(new GridLayoutManager(mContext, 3));
        videoLibraryAdapter = new VideoLibraryAdapter();
        mDataBinding.rvVideoLibraryList.setAdapter(videoLibraryAdapter);
        videoLibraryAdapter.addChildClickViewIds(R.id.ivVideoLibraryItemEdit);
        videoLibraryAdapter.setOnItemClickListener(this);
        videoLibraryAdapter.setOnItemChildClickListener(this);

        //新建影库弹框
        addVideoLibraryDialog();
        //删除弹框
        deleteDialog();
        //重命名弹框
        renameDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvGetPermission://获取权限
                getPermission();
                break;
            case R.id.tvAllVideo://全部视频
                getManagePermission();
                break;
            //新建影库弹框
            case R.id.tvDialogAddVideoLibraryConfirm://确定
                addVideoLibrary();
                break;
            case R.id.tvDialogAddVideoLibraryCancel://取消
                myAddVideoLibraryDialog.dismiss();
                break;
            //删除弹框
            case R.id.tvDialogDeleteConfirm://确定
                myDeleteDialog.dismiss();
                deleteMovieLibrary();
                break;
            case R.id.tvDialogDeleteCancel://取消
                myDeleteDialog.dismiss();
                break;
            //重命名弹框
            case R.id.tvDialogRenameConfirm://确定
                String name = dialogRename.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.showShort(R.string.please_input_video_library);
                    return;
                }
                myRenameDialog.dismiss();
                String path = PathUtils.getFilesPathExternalFirst() + Content.myVideo + "/" + listShow.get(selPosition);
                FileUtils.rename(path, name);
                getData();
                break;
            case R.id.tvDialogRenameCancel://取消
                myRenameDialog.dismiss();
                break;

        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == videoAdapter) {
            PlayLandscapeActivity.videoPath = videoAdapter.getItem(position).getPath();
            startActivity(PlayLandscapeActivity.class);
        } else if ((adapter == videoLibraryAdapter)) {
            if (position == 0) {
                //是否完成设置密码
                boolean isSetPassword = SPUtil.getBoolean(getContext(), Content.isHavePassword, false);
                if (isSetPassword) {
                    passwordDialog(false, false);
                } else {
                    passwordDialog(true, false);
                }
            } else if (position == listShow.size() - 1) {
                myAddVideoLibraryDialog.show();
            } else {
                VideoLibraryActivity.videoLibraryName = videoLibraryAdapter.getItem(position);
                startActivity(VideoLibraryActivity.class);
            }
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivVideoLibraryItemEdit://编辑
                if (position == 0) {
                    showChangePasswordDialog(view);
                } else {
                    selPosition = position;
                    showEditDialog(view);
                }
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        if (StkPermissionHelper.hasGrantMediaImgVideoPermission()) {
            getLocalVideoData();
            mDataBinding.llVideoNoPermission.setVisibility(View.GONE);
            mDataBinding.tvAllVideo.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.rvVideoList.setVisibility(View.GONE);
            mDataBinding.llVideoNoPermission.setVisibility(View.VISIBLE);
            mDataBinding.tvVideoNoData.setVisibility(View.GONE);
            mDataBinding.tvAllVideo.setVisibility(View.GONE);
            mDataBinding.tvLocalVideoSize.setVisibility(View.GONE);
        }
        getData();
    }

    private void addVideoLibrary() {
        String categoryName = dialogAdd.getText().toString();
        if (TextUtils.isEmpty(categoryName)) {
            ToastUtils.showShort(R.string.please_input_video_library);
            return;
        }
        myAddVideoLibraryDialog.dismiss();
        String path = PathUtils.getFilesPathExternalFirst() + Content.myVideo + "/" + categoryName;
        if (FileUtils.isFileExists(path)) {
            ToastUtils.showShort(getString(R.string.video_library_is_exist));
        } else {
            FileUtils.createOrExistsDir(path);
            ToastUtils.showShort(getString(R.string.add_video_library_suc));
        }
        getData();
    }

    private void deleteMovieLibrary() {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        String path = PathUtils.getFilesPathExternalFirst() + Content.myVideo + "/" + listShow.get(selPosition);
                        //从此文件夹删除
                        FileUtils.delete(path);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        getData();
                        dismissDialog();
                        startActivity(HomeActivity.class);
                        ToastUtils.showShort(getString(R.string.delete_suc));
                    }
                });
            }
        }, 1000);
    }

    private void getData() {
        listShow.clear();
        String path = PathUtils.getFilesPathExternalFirst() + Content.myVideo;
        List<File> files = FileUtils.listFilesInDir(path);
        listShow.add(PathUtils.getFilesPathExternalFirst() + Content.myPrivacy);
        if (files.size() > 0) {
            for (File file : files) {
                listShow.add(file.getName());
            }
        }
        listShow.add("");
        if (listShow.size() > 0) {
            videoLibraryAdapter.setList(listShow);
            mDataBinding.rvVideoLibraryList.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.rvVideoLibraryList.setVisibility(View.GONE);
        }
    }

    private void getManagePermission() {
        StkPermissionHelper.reqManageExternalStoragePermission().reqPermissionDesc(getString(R.string.get_manage_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                startActivity(LocalVideoActivity.class);
            }
        }).request();
    }

    private void getPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO)
                .reqPermissionDesc(getString(R.string.get_video_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        getLocalVideoData();
                    }
                }).request();
    }

    //获取视频和图片数据
    private void getLocalVideoData() {
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.VIDEO);
                emitter.onNext(listSys);
            }

            @Override
            public void accept(List<SelectMediaEntity> selectMediaEntities) {
                if (selectMediaEntities.size() > 0) {
                    long size = 0;
                    for (SelectMediaEntity selectMediaEntity : selectMediaEntities) {
                        size += selectMediaEntity.getSize();
                    }
                    videoAdapter.setList(selectMediaEntities);
                    mDataBinding.rvVideoList.setVisibility(View.VISIBLE);
                    mDataBinding.tvVideoNoData.setVisibility(View.GONE);
                    mDataBinding.tvLocalVideoSize.setText(getString(R.string.video_num, selectMediaEntities.size(), ConvertUtils.byte2FitMemorySize(size, 1)));
                } else {
                    mDataBinding.rvVideoList.setVisibility(View.GONE);
                    mDataBinding.tvVideoNoData.setVisibility(View.VISIBLE);
                    mDataBinding.tvLocalVideoSize.setText(getString(R.string.video_num, 0, "0.0B"));
                }
                mDataBinding.llVideoNoPermission.setVisibility(View.GONE);
                mDataBinding.tvAllVideo.setVisibility(View.VISIBLE);
                mDataBinding.tvLocalVideoSize.setVisibility(View.VISIBLE);
            }
        });
    }

    //新建影库弹框
    private void addVideoLibraryDialog() {
        myAddVideoLibraryDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_video_library, null);
        myAddVideoLibraryDialog.setContentView(inflate);
        myAddVideoLibraryDialog.setCancelable(true);
        Window dialogWindow = myAddVideoLibraryDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogAddVideoLibraryConfirm);
        TextView cancel = inflate.findViewById(R.id.tvDialogAddVideoLibraryCancel);
        dialogAdd = inflate.findViewById(R.id.etDialogAddVideoLibraryText);
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    private void showEditDialog(View view) {
        EditDialog editDialog = new EditDialog(mContext);
        editPopup = new XPopup.Builder(mContext).popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .atView(view).hasShadowBg(true) // 去掉半透明背景
                .asCustom(editDialog);
        editPopup.show();
        editDialog.setListener(new EditDialog.Ilistener() {
            @Override
            public void clickDelete() {
                editPopup.dismiss();
                myDeleteDialog.show();
            }

            @Override
            public void clickEdit() {
                editPopup.dismiss();
                dialogRename.setText(listShow.get(selPosition));
                myRenameDialog.show();
            }
        });
    }

    //删除弹框
    private void deleteDialog() {
        myDeleteDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_delete, null);
        myDeleteDialog.setContentView(inflate);
        myDeleteDialog.setCancelable(true);
        Window dialogWindow = myDeleteDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogDeleteConfirm);
        TextView cancel = inflate.findViewById(R.id.tvDialogDeleteCancel);
        TextView tip = inflate.findViewById(R.id.tvDialogDeleteTip);
        tip.setText(getString(R.string.is_delete_video_library));
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    //重命名弹框
    private void renameDialog() {
        myRenameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_rename, null);
        myRenameDialog.setContentView(inflate);
        myRenameDialog.setCancelable(true);
        Window dialogWindow = myRenameDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView right = inflate.findViewById(R.id.tvDialogRenameConfirm);
        TextView cancel = inflate.findViewById(R.id.tvDialogRenameCancel);
        TextView title = inflate.findViewById(R.id.tvDialogRenameTitle);
        title.setText(getString(R.string.edit_video_library_name));
        dialogRename = inflate.findViewById(R.id.etDialogRenameText);
        dialogRename.setHint(getString(R.string.input_video_library_name));
        right.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    private void answerDialog(boolean isForget) {
        SetAnswerDialog answerDialog = new SetAnswerDialog(mContext);
        answerDialog.isForget = isForget;
        answerDialog.setListener(new SetAnswerDialog.Listener() {
            @Override
            public void setPassword(String question, String answer) {
                //记录密码
                SPUtil.putBoolean(getContext(), Content.isHavePassword, true);
                SPUtil.putString(getContext(), Content.myPassword, pwd);
                SPUtil.putString(getContext(), Content.myProblem, question);
                SPUtil.putString(getContext(), Content.myAnswer, answer);
            }

            @Override
            public void changePassword() {
                passwordDialog(true, true);
            }
        });
        answerDialog.show();
    }

    private void passwordDialog(boolean isSetPassword, boolean isForgetPassword) {
        SetPasswordDialog passwordDialog = new SetPasswordDialog(mContext);
        passwordDialog.isSetPassword = isSetPassword;
        passwordDialog.setListener(new SetPasswordDialog.Listener() {
            @Override
            public void click(String password) {
                if (isForgetPassword) {
                    SPUtil.putString(getContext(), Content.myPassword, password);
                } else {
                    pwd = password;
                    answerDialog(false);
                }
            }

            @Override
            public void forgetPassword() {
                answerDialog(true);
            }
        });
        passwordDialog.show();
    }

    private void showChangePasswordDialog(View view) {
        ChangePasswordDialog changePasswordDialog = new ChangePasswordDialog(mContext);
        changePasswordPopup = new XPopup.Builder(mContext).popupPosition(PopupPosition.Bottom) //手动指定弹窗的位置
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .atView(view).hasShadowBg(true) // 去掉半透明背景
                .asCustom(changePasswordDialog);
        changePasswordPopup.show();

        changePasswordDialog.setListener(new ChangePasswordDialog.Ilistener() {
            @Override
            public void clickChangePassword() {
                changePasswordPopup.dismiss();
                answerDialog(true);
            }
        });
    }


}